
package cn.ito.zjgsu.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.ito.zjgsu.constant.StatusCode;
import cn.ito.zjgsu.domain.Person;
import cn.ito.zjgsu.domain.Role;
import cn.ito.zjgsu.domain.UserLogin;
import cn.ito.zjgsu.domain.wrapper.AuthorityWrapper;
import cn.ito.zjgsu.domain.wrapper.PersonWrapper;
import cn.ito.zjgsu.domain.wrapper.RoleWrapper;
import cn.ito.zjgsu.service.AuthorityService;
import cn.ito.zjgsu.service.PersonService;
import cn.ito.zjgsu.service.RolePermissionService;
import cn.ito.zjgsu.service.RoleService;
import cn.ito.zjgsu.service.UserService;
import cn.ito.zjgsu.utils.StatusCodeUtil;

@Controller
@RequestMapping("/admin")
public class RoleController {

	@Resource
	private RoleService roleService;

	@Resource
	private RolePermissionService rolePermissionService;

	@Resource
	private AuthorityService authorityService;

	@Resource
	private UserService userService;

	@Resource
	private PersonService personService;

	@Autowired
	private StatusCodeUtil statusCodeUtil;

	private static Logger logger = Logger.getLogger(RoleController.class);

	@RequestMapping("/role")
	public String index() {

		return "sys/roleMan";
	}

	// 查询所有角色
	@RequestMapping(value = "/role/roles/{pageNum}/{records}", method = RequestMethod.GET)
	@ResponseBody
	public String queryRoles(@PathVariable int pageNum, @PathVariable int records) {

		String data = RoleWrapper.list2JsonArray(roleService.queryRoles(pageNum, records)).toJSONString();
		return data;
	}

	// 查询角色已关联员工(未测试)
	@RequestMapping(value = "/role/{roleId}/{pageNum}/{records}", method = RequestMethod.POST)
	@ResponseBody
	public String queryRoleLinkAccount(@PathVariable int roleId, @PathVariable int pageNum, @PathVariable int records,
			@RequestParam String key) {
		return PersonWrapper.toJsonArrayString(PersonWrapper
				.wrapPersonList(roleService.queryPersonsLinkedRole(roleId, pageNum, records, null == key ? "" : key)));
	}

	// 查询角色未关联员工(未测试)
	@RequestMapping(value = "/role/{roleId}/{pageNum}/{records}/unrelated", method = RequestMethod.POST)
	@ResponseBody
	public String queryRoleUnrelatedAccount(@PathVariable int roleId, @PathVariable int pageNum,
			@PathVariable int records, @RequestParam String key) {
		return PersonWrapper.toJsonArrayString(PersonWrapper.wrapPersonList(
				roleService.queryPersonsDislinkedRole(roleId, pageNum, records, null == key ? "" : key)));
	}

	// 查询指定角色的所有信息 (暂时不用)
	@RequestMapping(value = "/role/roles/{roleId}", method = RequestMethod.GET)
	@ResponseBody
	public String queryRoleWrapper(@PathVariable int roleId) {
		return (roleService.queryRoleWrapperByRid(roleId)).toJsonObjectString();
	}

	// 更新角色
	@RequestMapping(value = "/role/{roleId}", method = RequestMethod.PUT)
	@ResponseBody
	public String updateRole(@PathVariable int roleId, @RequestParam String name,
			@RequestParam("Permissions") int[] permissions) {
		Role role = new Role();
		role.setRoleId(roleId);
		role.setRoleName(name);
		RoleWrapper rw = new RoleWrapper(role);
		rw.setPermissions(authorityService.queryPermissionsByPids(permissions));
		String status = roleService.updateRoleWrapper(rw);
		return statusCodeUtil.toJsonStatus(status);
	}

	// 刪除角色
	@RequestMapping(value = "/role/{roleId}", method = RequestMethod.DELETE)
	@ResponseBody
	public String deleteRole(@PathVariable int roleId) {
		String status = roleService.deleteRole(roleId);
		return statusCodeUtil.toJsonStatus(status);
	}

	// 查询所有权限
	@RequestMapping(value = "/permission/permissions", method = RequestMethod.GET)
	@ResponseBody
	public String queryAllRoles() {
		return AuthorityWrapper.toJsonArrayString(authorityService.findAllWrappedAuthorities());
	}

	// 新增角色
	@RequestMapping(value = "/role", method = RequestMethod.POST)
	@ResponseBody
	public String createRole(@RequestParam String name, @RequestParam int[] permissions) {
		Role role = new Role();
		role.setRoleName(name);
		RoleWrapper rw = new RoleWrapper();
		rw.setRole(role); // 不能用构造方法，此时roleid为null
		rw.setPermissions(authorityService.queryPermissionsByPids(permissions));
		String status = statusCodeUtil.toJsonStatus(roleService.createRole(rw));
		return status;
	}

	private List<UserLogin> getUsers(int roleId, Integer[] staffIds, int checkStatus, String key, Integer[] cancelIds) {
		List<Person> persons = getPersons(staffIds, checkStatus, key, cancelIds);
		// 1 创建帐户 关联角色
		List<UserLogin> users = new ArrayList<UserLogin>();
		if(null != persons && !persons.isEmpty()){
			for (Person p : persons) {
				UserLogin user = new UserLogin();
				user.setRoleId(roleId); // 关联角色
				user.setPersonId(p.getPersonId()); // 关联员工
				userService.generateUser(user);
				users.add(user);
			}
		}
		
		return users;
	}

	private List<Person> getPersons(Integer[] staffIds, int checkStatus, String key, Integer[] cancelIds) {
		if (checkStatus == 1) {
			List<Person> persons = personService.queryAllPerson();
			List<Integer> allpids = new ArrayList<Integer>();
			for (Person person : persons) {
				allpids.add(person.getPersonId());
			}
			if(null != cancelIds){
				allpids.removeAll(Arrays.asList(cancelIds));
			}
			staffIds = new Integer[allpids.size()];
			for (int i = 0; i < allpids.size(); i++) {
				staffIds[i] = allpids.get(i);
			}
		} else if (checkStatus == 0) {
			// staffIds = staffIds;
		} else {
			logger.warn("checkStatus!=1&&!=0");
		}
		List<Person> persons = personService.queryPidsByPidssandKey(staffIds, key);
		return persons;
	}
	// 以下未测试

	// 关联员工
	@RequestMapping(value = "/role/{roleId}/staffs", method = RequestMethod.POST)
	@ResponseBody
	public String linkPerson(@PathVariable int roleId, @RequestParam(value = "staffIds",required = false) Integer[] staffIds, @RequestParam int checkStatus,
			@RequestParam String key, @RequestParam(value = "cancelIds",required = false) Integer[] cancelIds) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			List<UserLogin> users = getUsers(roleId, staffIds, checkStatus, key, cancelIds);
			userService.insertUsers(users);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			e.printStackTrace();
			status = StatusCode.FAILURE_STATUS;
		}
		return statusCodeUtil.toJsonStatus(status);
	}

	// 取消关联员工

	@RequestMapping(value = "/role/{roleId}/staffs", method = RequestMethod.DELETE)
	@ResponseBody
	public String dislinkPerson(@PathVariable int roleId, @RequestParam(value = "staffIds" ,  required=false) Integer[] staffIds,
			@RequestParam int checkStatus, @RequestParam String key, @RequestParam(value = "cancelIds",  required=false) Integer[] cancelIds) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			List<Person> persons = getPersons(staffIds, checkStatus, key, cancelIds);
			List<Integer> pids = new ArrayList<Integer>();
			if(null!= persons && !persons.isEmpty()){
				for (Person p : persons) {
					pids.add(p.getPersonId());
				}
			}
			List<UserLogin> users = userService.queryUsersBypidsandRoleId(pids, roleId);
			userService.deleteUsers(users);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			e.printStackTrace();
			status = StatusCode.FAILURE_STATUS;
		}
		return statusCodeUtil.toJsonStatus(status);
	}

}
